/*========================全局变量=================================================*/
var nResult = 0; // 记录连接结果
// 测试环境、本地环境用的接口地址
// var baseUrl = "http://118.190.175.96:8081";
// 正式环境用的接口地址
var baseUrl = "https://cc1.dcrm.cn:8443";
var url = baseUrl + "/JNAPI/tel";
var statementUrl = baseUrl + "/JNAPI";//获取事件url
// console.log(url)
// console.log(statementUrl)
var strGH = telephoneNumber; //工号（需要设置）
var strPWD = ""; //密码，为空即可
var strXM = "meng"; //姓名（需要设置）
var strFJH = extensionNumber; //分机号（需要设置）
var strShowNum = "0"; //外拨对方显示号码（需要设置）
var strWorkerGroup = "work"; //工作组2（需要设置）
var strIsAdmin = "0"; //是否是管理员 0：否 1：是（需要设置）
var strSLCType = "3"; //座席类型 0:硬座席 1:软座席, 2 IP座席, 3 外线座席
var timer = null;
var FlowID = "101"; //外呼流程号
var CallSerialNumber = ""; //序列号
var afterWorkTimeOut = 9999; //话后处理时常，单位 ： 秒
var WorkTimeOut = 0; //>0表示小休n秒后自动示闲
var workstate = 1; //坐席签入后默认状态
var nTimer = 0; //时间记数
var blTimer = true; //是否可以记时
var blCalling = false; //是否有电话正在呼入
var blLogined = false; //是否登录
var userStatus = 1; //默认为1
var blCallin = false; //是否电话呼入
var blCallOut = false; //是否外拨中
var strConfNOs = ""; //会议号码
var arrSLCList = new Array(); //座席状态列表
var callinTimer = null; //座席状态列表
var nCount = 0; //统计日志行数
var nQueue = 0; //统计排队个数
var strIsConf = "1"; //是否启用会议
var blIsConf = (strIsConf == "1" ? true : false);
var startFangWei = false // 是否启用话机接口


/*========================通用函数=================================================*/

//拷贝按钮
function CopyUrl() {

    /*let url = document.querySelector("input[name='txtTelNO']");
    url.select(); // 选择对象*/
    document.execCommand("Copy");
}

//获取参数值
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return unescape(pair[1]);
        }
    }
    return (false);
}


// 设置按钮状态
function funEnabledBtn(vStrBtnID, vBlEnabled
) {

    var objBtn = document.getElementById(vStrBtnID);
    if (objBtn) objBtn.disabled = !vBlEnabled;
    funChangeImg(vStrBtnID, vBlEnabled);


}

//替换图片按钮的图片
function funChangeImg(vOjb, vBool
) {
    var imName = "";
    if (vOjb != null) {
        imName = vOjb.substring(3, vOjb.length); //载取按钮名，作图片名
        if (!vBool)
            imName = imName + "Un.gif";
        else
            imName = imName + ".gif";
    }
    try {
        document.getElementById(vOjb).src = "/images/callCenter/" + imName;
    } catch (e) {
    }
}

//设置按钮是否显示
function funDisplayBtn(vStrBtnID, vBlDisplay
) {
    var objBtn = document.getElementById(vStrBtnID);
    if (objBtn) {
        if (vBlDisplay)
            objBtn.style.display = "block";
        else
            objBtn.style.display = "none";
    }
}

/**/

//设置操作名称
function setActionName(vStrInfo) {
    try {
        var objDiv = document.getElementById("divAction");
        if (objDiv) {
            objDiv.innerText = vStrInfo;
            //console.log(vStrInfo)
        }
    } catch (e) {
    }
}

//设置计时器
function setTimer() {
    //log(blTimer +"  " + nTimer)
    if (!blTimer) return;
    var nHour = parseInt(nTimer / 3600);
    var nTmp = nTimer % 3600;
    var nMintue = parseInt(nTmp / 60);
    var nSecond = nTmp % 60;
    var strTimer = funAddZero(nHour) + ":" + funAddZero(nMintue) + ":" + funAddZero(nSecond);
    // var objTimer = document.getElementById('lblTimer');
    // if (objTimer) objTimer.innerText = strTimer;
    nTimer++;

    if (callinTimer === null) {
        callinTimer = window.setInterval("setTimer()", 1000);
    }
}


//管理座席状态
function funMgrSLC(vStrCaller, vStrCallee, vCallInTime, vStrStatus
)//,vStrUserName,vStrWorkName,vStrSLCStatus,vStrLoginTime,vStrCallEndTime,vBlAdd)
{
    vStrCaller = vStrCaller.substring(0, vStrCaller.indexOf(","));
    var nIndex = getCallerIndex(vStrCaller);
    // 如果有，则更新
    if (nIndex > -1) {

        if (arrSLCList[nIndex][1].Length == 0 && vStrCallee != "") arrSLCList[nIndex][1] = vStrCallee;
        if (arrSLCList[nIndex][2].Length == 0 && vStrCallee != "") arrSLCList[nIndex][2] = objSLC.CallInTime;
        if (vStrStatus != "") {
            arrSLCList[nIndex][3] = vStrStatus;
        }
    } else {
        writeInfo("new funMgrSLC");
        arrSLCList[arrSLCList.length] = new Array(vStrCaller, vStrCallee, vCallInTime, vStrStatus, "", "", "", "", "");
    }
}

function funMgrSLC1(vStrCaller, vStrUserName, vStrWorkName, vStrSLCStatus, vStrLoginTime, vStrCallEndTime, vBlAdd
) {
    if (!isNumber(vStrCaller)) return;
    var nIndex = getCallerIndex(vStrCaller);

    // 如果有，则更新
    if (nIndex > -1) {
        arrSLCList[nIndex][4] = vStrUserName;
        arrSLCList[nIndex][5] = vStrWorkName;
        arrSLCList[nIndex][6] = vStrSLCStatus;
        arrSLCList[nIndex][7] = vStrLoginTime;
        arrSLCList[nIndex][8] = vStrCallEndTime;
    } else {//writeInfo("new funMgrSLC1");
        arrSLCList[arrSLCList.length] = new Array(vStrCaller, "", "", "空闲", vStrUserName, vStrWorkName, vStrSLCStatus, vStrLoginTime, vStrCallEndTime);
    }
}

//更新座席状态
function updateSLCList(vStrCaller, vStrStatus, vStrCallerID
) {

    if (!isNumber(vStrCaller)) return;
    var nIndex = getCallerIndex(vStrCaller);
    if (nIndex < 0) return;

    arrSLCList[nIndex][3] = vStrStatus;
}

//更新座席状态
function updateSLCListEx(vStrCaller, vStrSLCStatus
) {
    if (!isNumber(vStrCaller)) return;
    var nIndex = getCallerIndex(vStrCaller);
    if (nIndex < 0) return;

    arrSLCList[nIndex][6] = vStrSLCStatus;
}

//根据电话号码索引其所在数据组位置
function getCallerIndex(vStrCaller) {
    try {
        var nIndex = -1;
        for (var i = 0; i < arrSLCList.length; i++) {
            if (arrSLCList[i][0] == vStrCaller) {
                nIndex = i;
                break;
            }
        }
        return nIndex;
    } catch (e) {
    }
}

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//写出系统执行过程
function writeInfo(vStrMsg) {
    try {
        var objTxt = document.getElementById("txtInfo");
        var newDiv = document.createElement("span");
        var newDivs = document.createElement("div");
        newDiv.innerText = new Date().Format("yyyy-MM-dd HH:mm:ss") + "  " + vStrMsg
        newDivs.className = "doInput";
        newDivs.style.textAlign = "left";
        newDivs.appendChild(newDiv)
        if ($(".doInput")[0] === undefined) {
            objTxt.appendChild(newDivs)
        } else {
            objTxt.insertBefore(newDivs, $(".doInput")[0]);
        }
        /* objTxt.insertBefore(newDiv)
         objTxt.insertBefore(br)*/
        //$("#txtInfo").scrollTo('100%')
        //objTxt.value = vStrMsg + "\r\n" + objTxt.value;
        //nCount = nCount + 1;
        /*  if (nCount > 10000) //大于100行清空
          {
              objTxt.value = "";
              nCount = 0;
          }*/
    } catch (e) {
        console.log(e)
    }
}

//统计排队数
function CountQueue() {
    nQueue = getUserQueueInfo(strWorkerGroup);
    // document.getElementById("lblQueue").innerText = nQueue;
    window.setTimeout("CountQueue()", 2000);
}

//直接外拨号码(可供外部其它页面调用)
function funCallPhone(vNum) {
    if (blCalling) {
        alert('通话中，不能进行外拨');
        return;
    }
    if (nResult != 1) return;
    if (!blLogined) {
        alert('未签入状态，不能外拨');
        return;
    }
    document.getElementById("txtTelNO").value = vNum;
    funBtnCall();
}

//班长席所需的按钮是否可用
function funAdminBtnEnable(vBool) {
    funEnabledBtn("btnToListen", vBool);
    funEnabledBtn("btnToInsert", vBool);
    funEnabledBtn("btnToBreak", vBool);
    funEnabledBtn("btnToLogout", vBool);
    funEnabledBtn("btnLogOut", vBool)
}

//设置所有按钮是否可用
function funAllBtnEnabled(vBool) {
    funEnabledBtn("btnLogin", vBool);         //设置按钮状态
    funEnabledBtn("btnLogOut", vBool);
    funEnabledBtn("btnCall", vBool);
    funEnabledBtn("btnHold", vBool);
    funEnabledBtn("btnReHold", vBool);
    funEnabledBtn("btnTran", vBool);
    funEnabledBtn("btnMeeting", vBool);
    funEnabledBtn("btnFax", vBool);
    funEnabledBtn("btnSet", vBool);
    funEnabledBtn("btnAnswer", vBool);
    funEnabledBtn("btnSoftHook", vBool);
    funEnabledBtn("btnReady", vBool);
    funEnabledBtn("btnLeave", vBool);
    if (strIsAdmin == "1") //如果是班长席，设置监控按钮都不可用
        funAdminBtnEnable(vBool);
}

//系统复位
function funReStart() {
    blTimer = false;
    blCalling = false;
    // 修改按钮状态
    funEnabledBtn("btnSoftHook", false);
    funEnabledBtn("btnHold", false);
    funEnabledBtn("btnReHold", false);
    funDisplayBtn("btnReHold", false);
    funEnabledBtn("btnCall", true);
    funEnabledBtn("btnTran", false);
    funEnabledBtn("btnOneKey", false);
    blCallin = false;
    blCallOut = false;
    window.clearTimeout(timer);
    if (blIsConf)    //如果开启了会议功能
    {
        funEnabledBtn("btnMeeting", true);
    }
    if (blLogined) {
        funEnabledBtn("btnLeave", true);
        funEnabledBtn("btnReady", true);
    }
    funEnabledBtn("btnLogin", true);
    funEnabledBtn("btnLogOut", true);
    funEnabledBtn("btnAnswer", false);
    //清空会议号码
    strConfNOs = "";
    //setActionName("就绪");
}

/*========================按钮单击事件=========================================================*/

// 签入
function funbtnLogin() {
    try {
        funLogin();
    } catch (e) {
        alert("异常错误，请重试。" + e.description);
    }
}

//签出
function funbtnLogout() {
    try {
        funLogout();
    } catch (e) {
        alert("异常错误，请重试。" + e.description);
    }
}

// 小休
function funBtnLeave() {
    try {
        funLeave();
        setActionName("小休");
    } catch (e) {
        alert("异常错误，请重试。" + e.description);
    }
}

//就绪
function funBtnReady() {
    try {
        funReady();
        setActionName("就绪");
    } catch (e) {
        alert("异常错误，请重试。" + e.description);
    }
}

//应答
function funBtnAnswer() {
    funAnswer();
}

//外拨
function funBtnCall() {
    $('#sureBtn, #sureBtn2').prop('disabled', true);
    // var strCallee = document.all.txtTelNO.value.Trim();
    // 去除全部空格
    var strCallee = document.all.txtTelNO.value.replace(/\s*/g,'');
    console.log("外拨号码：" + strCallee);

    // 判断外拨号码为空
    if (strCallee.length == 0) {
        $.alert({
            title: '系统提示',
            content: '请输入要呼叫的号码。'
        });
        // document.all.txtTelNO.select();
        // document.all.txtTelNO.focus();
        return;
    }

    // 判断外拨号码是否为数字和短横线
    var numberTest = /^([0-9-\s]+)$/;
    if (!numberTest.test(strCallee)) {
        $.alert({
            title: '系统提示',
            content: '请输入正确号码：只能包括数字和 \'-\'',
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function () {
                        document.all.txtTelNO.value = ''
                    }
                }
            }
        });
        return;
    }

    if (followSource == 4 || followSource == 6) {    // 拨打核实电话 或 一机多用
        funCall(strCallee);
        // $('#editFollowInfo').show(0);
    } else if(followSource == 7){
        $.ajax({
            url: '/internalTrainingManager/selectNxContactByContactInformation',
            type: 'POST',
            dataType: "json",
            data: {
                contactInformation : strCallee,
                customerId:  $('#callCustomerId').val(),
            },
            success: (function (data) {
                if (data.code == "000000") {
                    if (choseNumber == undefined && allContactInfo.length) {
                        for (var i = 0; i < allContactInfo[0].choseInfo.length; i++) {
                            if (strCallee == allContactInfo[0].choseInfo[i]) {
                                choseInfo.choseInfo = allContactInfo[0].choseInfo[i];
                                choseInfo.contactName = allContactInfo[0].contactName;
                                choseInfo.contactId = allContactInfo[0].contactId;
                                break;
                            }
                        }
                    }
                    console.log('手动输入联系方式的联系人相关数据：', choseInfo);
                    $('.tell-name').fadeIn().find('span').html(choseInfo.contactName || data.data);
                    funCall(strCallee);

                    // $('#editFollowInfo').show(0);
                } else {
                    $.alert("联系人不存在，请确认！");
                    return;
                }
            })
        });
    } else {
        $.ajax({
            url: '/systemManager/callManager/isContactExist',
            type: 'POST',
            dataType: "json",
            data: {
                contactInformation : strCallee,
                followSource : followSource,
                callId : $('#callId').val()
            },
            success: (function (data) {
                if (data.code == "000000") {
                    if (choseNumber == undefined && allContactInfo.length) {
                        for (var i = 0; i < allContactInfo[0].choseInfo.length; i++) {
                            if (strCallee == allContactInfo[0].choseInfo[i]) {
                                choseInfo.choseInfo = allContactInfo[0].choseInfo[i];
                                choseInfo.contactName = allContactInfo[0].contactName;
                                choseInfo.contactId = allContactInfo[0].contactId;
                                break;
                            }
                        }
                    }
                    console.log('手动输入联系方式的联系人相关数据：', choseInfo);
                    $('.tell-name').fadeIn().find('span').html(choseInfo.contactName || data.data);
                    funCall(strCallee);

                    // $('#editFollowInfo').show(0);
                } else {
                    $.alert("联系人不存在，请确认！");
                    return;
                }
            })
        });
    }


}

//软挂机
function funBtnSoftHook() {

    funSoftHook();
}

//通话保持
function funBtnHold() {
    if (!blCallin) {
        return;
    }
    try {
        funSetHold();
        setActionName("保持");
    } catch (e) {
        alert("异常错误，请重试。" + e.description);
    }
}

//恢复
function funBtnReHold() {
    if (!blCallin) {
        return;
    }
    try {
        funSetUnHold();
        setActionName("通话");
    } catch (e) {
        alert("异常错误，请重试。" + e.description);
    }
}

// 三方会议
function funBtnConf() {
    // if (nResult != 1) return;
    //openWin("TelMeeting.html", "telMeeting", 320, 230);
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: "会议",
        url: "/front/callCenter/TelMeeting"
    }, true);
    setActionName("会议");
}

// 转接
function funBtnTrans() {
    //if (nResult != 1) return;
    funReflashAgentStateList(); //刷新座席状态列表
    openWin("TelTrans.html", "telTrans", 420, 420);
    //funToTrans(1002);
    setActionName("转接");
}

// 监听
function funBtnToListen() {
    if (nResult != 1) return;
    arrSLCList = new Array();
    funReflashAgentStateList(); //刷新座席状态列表
    openWin1("TelToListen.html", "telToListen", 420, 420);
    setActionName("监听");
}

// 强插
function funBtnToInsert() {
    if (nResult != 1) return;
    arrSLCList = new Array();
    funReflashAgentStateList(); //刷新座席状态列表
    openWin1("TelToInsert.html", "telToInsert", 420, 420);
    setActionName("强插");
}

// 强拆
function funBtnToBreak() {
    if (nResult != 1) return;
    funReflashAgentStateList(); //刷新座席状态列表
    openWin1("TelToBreak.html", "telToBreak", 420, 420);
    setActionName("强拆");
}

// 强签
function funBtnToLogout() {
    if (nResult != 1) return;
    funReflashAgentStateList(); //刷新座席状态列表
    openWin1("TelToLogout.html", "telToLogout", 420, 420);
    setActionName("强签");
}

// 设置
function funBtnSet() {
    if (blCalling) {
        alert('通话中，不能进行设置。');
        return;
    }
    funGetSLCType();//先获取座席类型
    //
    // var strValue = window.showModalDialog("subHtml/TelSetType.html", strSLCType, "status:no;dialogWidth=300px;status:no;scrollbars:no;dialogHeight:120px");

    if (strValue == null) return;
    if (strValue.Trim().length == 0) return;
    if (strValue != "0" && strValue != "1") {
        alert('参数错误，请重试。');
        return;
    }
    funSetSLCType(strValue); //调用接口
}

//退出页面时调用
function frm_UnLoad() {
    if (blLogined) {
        funLogout();
    }
}


/*==============================调用接口====================================================================*/

// 启用连接接口
function funStart() {
    LogIn();
    //打印日志
    recivePacket(); //接收CTI服务器的数据包
    CountQueue();   //调用接收排队数参数
    editWork();   //调用接收排队数参数
    editFJ();   //调用接收排队数参数
    writeInfo("连接服务器 \t当前工号::" + strGH + "\t当前分机号:" + strFJH + "\t当前工作组:" + strWorkerGroup);
    //调用接收排队数参数
    funEnabledBtn("btnLogin", true);
    funEnabledBtn("btnReady", false);
    funEnabledBtn("btnHold", false);
    funEnabledBtn("btnHold", false);
    funEnabledBtn("btnAnswer", false);
    funEnabledBtn("btnSoftHook", false);
}

function editWork() {
    $("#lblGH").text(strGH);
    log("当前工号" + strGH)
}

function editFJ() {
    $("#lblFJH").text(strFJH)
    log("当前分机号" + strFJH)
    log("当前url" + baseUrl)
}

function obj2string(o) {
    var r = [];
    if (typeof o == "string") {
        return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    }
    if (typeof o == "object") {
        if (!o.sort) {
            for (var i in o) {
                r.push(i + ":" + obj2string(o[i]));
            }
            if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
                r.push("toString:" + o.toString.toString());
            }
            r = "{" + r.join() + "}";
        } else {
            for (var i = 0; i < o.length; i++) {
                r.push(obj2string(o[i]))
            }
            r = "[" + r.join() + "]";
        }
        return r;
    }
    return o.toString();
}

/**
 * 功能：获取呼叫记录信息
 * */
function getCallInfo(str) {
    // 获取选择的联系人和相关信息
    // console.log(choseInfo, choseNumber, followSource, str, str.CallSerialNumber);
    // console.log('---------------------------------------------------------', str.CallSerialNumber, choseInfo)
    var callOutLog = getCallOutLogByID(str.CallSerialNumber);

    // callOutLog.RetCode: 1成功  0失败  1异常  -3参数异常  -11密钥无效
    // 通话失败取消向呼叫中心添加数据
    if (callOutLog.RetCode != 1) {
        return;
    }
    // console.log('获取到的通话记录数据：', callOutLog);

    //客户联系人ID
    var contactId;
    //联系人姓名
    var contactName;
    //联系方式
    var contactInformation;
    if (choseInfo) {
        //客户联系人ID
        contactId = choseInfo.contactId;
        //联系人姓名
        contactName = choseInfo.contactName;
        //联系方式
        contactInformation = choseInfo.choseInfo ? choseInfo.choseInfo : $('#txtTelNO').val();
    } else {
        //联系方式
        contactInformation = $('#txtTelNO').val();
    }
    //客户ID
    var customerId = $('#callCustomerId').val();
    //通话时长
    var callDuration = callOutLog.data[0].AnswerHold;
    //通话录音
    var callRecord = callOutLog.data[0].Recordfilepath;
    //呼叫中心外呼表唯一ID
    var callSerialNumber = callOutLog.data[0].CallSerialNumber;
    //跟进来源：0-线索跟进；1-客户跟进；2-单品客户跟进；4-核实电话;
    var followSourceVal = followSource;
    var customerTypeVal = customerType;
    if (followSourceVal == 0) {
        var clueId = $('#callId').val();
        contactId = "";
    } else if (followSourceVal == 2) {
        var singleProductCustomerId = $('#callId').val();
        contactId = "";
    }

    var jsonData = {
        "contactId": contactId,
        "contactName": contactName,
        // "contactInformation": contactInformation,
        // 获取远程返回数据的外拨电话号码(解决直接话机外拨电话无法获取到外呼号码问题);
        "contactInformation": callOutLog.data[0].CalleeID,
        "customerId": customerId,
        "callDuration": callDuration,
        "callRecord": callRecord,
        "callSerialNumber": callSerialNumber,
        "followSource": followSourceVal,
        "singleProductCustomerId": singleProductCustomerId,
        "clueId": clueId,
        "customerType": customerTypeVal
    };

    console.log('获取到的外拨相关信息：', jsonData);
    let insideJson = {
        'customerId':customerId,
        'customerName':'',
        'contactId':followSourceVal==7?contactId:'',
        'contactName':contactName,
        'contactInformation':callOutLog.data[0].CalleeID,
        'callDuration':callDuration
    }

    if (followSourceVal == 4) {     // 拨打核实电话
        $.ajax({
            url: '/verifyPhone/callVerifyPhone',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if (data.code == '000000') {
                    console.log("callVerifyPhone success ");
                    console.log('获取到的核实电话id：', verifyId);
                    // 核实电话返回id 用于保存核实电话时跟进记录
                    var verifyId = data.data;
                    $('#followInfoSource').val(verifyId);
                    // 确认是否获取跟进id
                    if (verifyId) {
                        $('#sureBtn, #sureBtn2').prop('disabled', false);
                    }
                }
            })
        });
    } if (followSourceVal == 6) {   // 拨打一机多用电话
        $.ajax({
            url: '/clueFollow/oneMachineMultipleUses',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if (data.code == '000000') {
                    $('#followInfoId').val(data.data);
                    console.log("oneMachineMultipleUses success ");
                    console.log('获取到的跟进id：', data.data);
                    if (data.data) {
                        $('#sureBtn, #sureBtn2').prop('disabled', false);
                    }
                }
            })
        });
    }  if (followSourceVal == 7 || followSourceVal == 8) {   // 内训
        $.ajax({
            url: '/internalTrainingManager/onlineFollow',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(insideJson),
            success: (function (data) {
                if (data.code == '000000') {
                    $('#followInfoId').val(data.data);
                    console.log("oneMachineMultipleUses success ");
                    console.log('内训/外训：', data.data);
                    if (data.data) {
                        $('#sureBtn').prop('disabled', false);
                    }
                }
            })
        });
    } else {
        $.ajax({
            url: '/clueFollow/customerOnlineFollowUp',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if (data.code == '000000') {
                    $('#followInfoId').val(data.data);
                    console.log("customerOnlineFollowUp success ");
                    console.log('获取到的跟进id：', data.data);
                    if (data.data) {
                        $('#sureBtn, #sureBtn2').prop('disabled', false);
                    }
                }
            })
        });
    }
}

// 启动数据接收 1ms接收一次-- - 此处要特别注意
function recivePacket() {
    var str = getAgentEvent(strFJH);
    if (str != null) {
        // console.log(str.CMD )
        if (str.CMD != null) {
            log(str.CMD + "\t" + str.Type + "\t" + str.Exception)
        }

        if (str.CMD == "ChannelState") {
            if (str.Type == "RingTo") {
                //振铃
                //vStrCaller, vStrCallee, vStrRecFile, vStrSerial
                CallSerialNumber = str.CallSerialNumber;
                eventRingTo(str.Caller, str.Callee, str.EventParam, str.RecordFile);
                console.log('RingTo事件', str);
                // getCallOutLogByID(str.CallSerialNumber);
            } else if (str.Type == "RingBack") {
                //vStrCaller, vStrCallee, vStrRecFile, vStrSerial
                // writeInfo("RingBack事件  ::::   "+  obj2string(str));
                eventRingBack(str.Caller, str.Callee, str.RecordFile, str.RecordFile);
                console.log('RingBack事件', str);
            } else if (str.Type == "Answer") {
                //vStrCaller
                eventOffHook(strFJH);
                // writeInfo("Answer事件  ::::   "+obj2string(str));
                console.log('Answer事件', str);
            } else if (str.Type == "HangUp") {
                //HangUp
                eventHook(strFJH, str);
                // writeInfo("HangUp事件  ::::   "+obj2string(str));
                setActionName("挂机");
                console.log('HangUp事件', str, strFJH);
                // getCallOutLogByID(str.CallSerialNumber);
            }
        } else if (str.CMD == "LogInOrOut") {
            //签入签出log
            if (str.LoginType === "1") {
                if (str.retCode === "1") {
                    log("签入请求发送,开始发送心跳")
                    userStatus = 1
                    //将心跳交管给Web Worker 支持
                    startWorker()
                    //c = window.setInterval("LogInON()", 15000);
                    writeInfo("分机签入成功，当前工号:" + strGH + "\t分机号:" + strFJH + "\t外显号码" + strShowNum)
                    eventUsrLogin('vStrQueueName', strGH, strPWD, strShowNum, 1, '成功');
                } else {
                    var cuowu;
                    log("签入失败,失败原因" + str.Exception)
                    if (str.Exception === "repeat_login") {
                        cuowu = "\t重复签入"
                    }
                    //超时自动签出问题
                    if ("net_timeout".indexOf(str.Exception) >= 0) {
                        //心跳出现超时！！！
                        writeInfo("检测心跳超时处理")
                        console.error(`检测心跳超时处理${new Date()}`)
                        // c = window.setInterval("LogInON()", 15000);
                        //startWorker()
                        //重新处理心跳
                    }
                    writeInfo("分机签入失败，失败原因:" + cuowu)
                }

            } else if (str.LoginType === "0") {
                // window.clearInterval(c);
                stopWorker()
                writeInfo("分机签出成功，当前工号:" + strGH + "\t分机号:" + strFJH + "\t外显号码" + strShowNum)
                eventUsrLogout('vStrQueueName', strGH, strPWD, '15047177101', 1, '成功');
            }
        } else if (str.CMD == "PlayFlie") {

        } else if (str.CMD == "UpdateAgentState") {
            //console.log(str.WorkState)
            if (str.WorkState == "1") {
                eventReady(strFJH, str.retCode)
                userStatus = 1
                //置忙
            } else {
                if (str.WorkState == "6") {
                    userStatus = 6
                    //小休处理
                    eventLeave(strFJH, str.WorkState);
                } else if (str.WorkState == "2") {
                    userStatus = 2
                    //置忙
                    writeInfo("分机置忙成功，当前工号:" + strGH + "\t分机号:" + strFJH + "\t外显号码" + strShowNum)
                    eventLeave(strFJH, str.WorkState)
                } else {
                    //都是忙碌状态
                    if (str.WorkState === "3") {
                        userStatus = 3
                        writeInfo("设置处理");
                        setActionName("处理");
                    } else if (str.WorkState === "4") {
                        userStatus = 4
                        writeInfo("设置开会");
                        setActionName("开会");
                    } else if (str.WorkState === "5") {
                        userStatus = 5
                        writeInfo("设置培训");
                        setActionName("培训");
                    } else if (str.WorkState === "7") {
                        userStatus = 7
                        writeInfo("设置用餐");
                        setActionName("用餐");
                    } else if (str.WorkState === "8") {
                        userStatus = 8
                        writeInfo("设置调用");
                        setActionName("调用");
                    } else if (str.WorkState === "9") {
                        userStatus = 9
                        writeInfo("设置其他");
                        setActionName("其他");
                    }
                    funDisplayBtn("btnReady", true);
                    funDisplayBtn("btnLeave", false);
                }
            }

        }
    }
    window.setTimeout("recivePacket()", 500);
}

var w;

function startWorker() {
    log(typeof (Worker))
    log(typeof (w))
    if (typeof (Worker) !== "undefined") {

        w = new Worker("../js/callCenter/connetHert.js");


        var data = {
            "url": statementUrl, "WorkNumber": strFJH, "WorkGroup": strWorkerGroup, "WorkID": strGH
            , "PassWord": strPWD, "AfertWorkTimeOut": afterWorkTimeOut
            , "WorkState": userStatus
        }
        //传输数据
        w.postMessage(data);

        w.onmessage = function (event) {
            console.log(`心跳保持${new Date()}`)
            //document.getElementById("result").innerHTML=event.data;
        };
    } else {
        alert("暂不支持该浏览器，可能会出现自动签出现象！")
    }
}

function stopWorker() {
    if (typeof (w) !== "undefined") {
        w.terminate();
    }

}


// 登录接口
function funLogin() {
    //if (nResult != 1) return;
    if (strIsAdmin == "1") {
        alert("暂不支持组长权限");
    } else {
        var n = LogIn();
        if (n === "1") {
            writeInfo("发送签入指令");
        } else {
            writeInfo("发送签入指令");
        }

    }

}

// 退出接口
function funLogout() {
    //if (nResult != 1) return;
    var n = 0;
    if (blCallin || blCallOut)     //如果退出则，判断是否需要挂机
    {
        writeInfo("签出时软挂机");
    }
    n = LogOut();
    writeInfo("发送签出指令成功");
    funAdminBtnEnable(false);
    writeInfo("签出成功");
    funDisplayBtn("btnHold", true);
    funDisplayBtn("btnReHold", false);
    funDisplayBtn("btnLogin", true);
    funDisplayBtn("btnLogOut", false);
    funDisplayBtn("btnLeave", true);
    funDisplayBtn("btnReady", false);
    funAllBtnEnabled(false); //设置所有按钮不可用
    funEnabledBtn("btnLogin", true);
    blLogined = false;
    blCallOut = false;
    setActionName("未签入");
    funMgrSLC1(strShowNum, "", "", "", "", "", false);
}

// 小休接口
function funLeave() {
    if (UpdateAgentState(6) == 1) {
        writeInfo("发送小休指令成功");
        writeInfo("设置小休成功");
        funDisplayBtn("btnReady", true);
        funDisplayBtn("btnLeave", false);
        setActionName("小休");
    } else {
        writeInfo("发送小休指令失败");
    }
}

// 就绪接口
function funReady() {
    //if (nResult != 1) return;
    //var n = document.all.axDRSLC.drtReady("");
    if (UpdateAgentState(1) == 1) {
        writeInfo("发送就绪指令成功")
        funDisplayBtn("btnLeave", true);
        funDisplayBtn("btnReady", false);
        //setActionName("就绪");
    } else writeInfo("发送就绪指令失败");
}

// 应答接口
function funAnswer() {
    /*
    *
    *
    * 应答无接口
    *
    * */
    if (startFangWei) {
        //使用话机
        AnswerFangWei()
    } else {
        if (Answer(strFJH) === 1) {
            setActionName("应答");       //设置当前操作状态
            writeInfo("发送应答指令成功");
        } else {
            writeInfo("发送呼叫指令失败");
        }
    }


}

// 外拨接口
function funCall(vCallee) {
    //if (nResult != 1) return;
    var strCallee = vCallee;
    funRecCall(strCallee);                      // 写入外呼记录中
    LastPhone = strCallee;                      // 记录最近一次电话号码
    //var n = document.all.axDRSLC.drtAutoDial(101, 9, strShowNum, strCallee);
    var n = MakeCall(strCallee, strFJH);
    if (n == 1) {
        setActionName("回铃");           // 设置当前操作状态
        blCallOut = true;                       // 设置外拨状态
        var objTxt = document.getElementById("txtInfo");
        var newDivs = document.createElement("div");
        var newDiv = document.createElement("span");
        var newRed = document.createElement("span");
        var newEND = document.createElement("span");
        newDivs.className = "doInput"
        newDivs.style.textAlign = "left";
        newDiv.innerText = new Date().Format("yyyy-MM-dd HH:mm:ss") + " 外呼号码：["
        newRed.style.color = "red"
        newRed.innerText = strCallee
        newEND.innerText += "]"
        newDivs.appendChild(newDiv)
        newDivs.appendChild(newRed)
        newDivs.appendChild(newEND)
        if ($(".doInput")[0] === undefined) {
            objTxt.appendChild(newDivs)
        } else {
            objTxt.insertBefore(newDivs, $(".doInput")[0]);
        }

        //writeInfo("发送呼叫[" + strCallee + "]指令成功");
        funEnabledBtn("btnSoftHook", true);   // 设置挂机按钮为可用
        funEnabledBtn("btnLeave", false);     // 外呼状态中，不能设置为小休
    } else {
        writeInfo("发送呼叫[" + strCallee + "]指令失败");
    }
}

// 软挂机接口
function funSoftHook() {
    //if (nResult != 1) return;
    // var n = document.all.axDRSLC.drtHook(strFJH);
    //if (nResult != 1) return;

    var n = HangUp(strFJH);

    console.log("点击按钮挂机")
    // $('#sureBtn').prop('disabled', false);
    // 修改按钮状态
    funEnabledBtn("btnHold", false);
    funEnabledBtn("btnReHold", false);
    funDisplayBtn("btnReHold", false);
    funEnabledBtn("btnCall", true);
    funEnabledBtn("btnTran", false);
    funEnabledBtn("btnOneKey", false);
    blCallin = false;
    blCallOut = false;
    window.clearTimeout(timer);
    funEnabledBtn("btnLeave", true && blLogined);
    funEnabledBtn("btnReady", true && blLogined);
    funEnabledBtn("btnLogin", true);
    funEnabledBtn("btnLogOut", true);
    funEnabledBtn("btnAnswer", false);
    if (n == 1) {
        funReStart();
        document.getElementById("txtTelNO").value = "";  //清除号码框
        writeInfo("发送软挂机指令成功");
    } else {
        writeInfo("发送软挂机指令失败");
    }
}

// 保持接口
function funSetHold() {
    //var n = document.all.axDRSLC.drtHold();
    var n = Hold(strWorkerGroup, "hold");
    if (n == 1) {
        writeInfo("发送保持指令成功");
        funDisplayBtn("btnHold", false);
        funDisplayBtn("btnReHold", true);
        funEnabledBtn("btnReHold", true);
    } else {
        writeInfo("发送保持指令失败");
    }
}

// 恢复接口
function funSetUnHold() {
    //var n = document.all.axDRSLC.drtUnHold();
    var n = Hold(strWorkerGroup, "cancel");
    if (n == 1) {
        writeInfo("发送恢复指令成功");
        funDisplayBtn("btnHold", true);
        funDisplayBtn("btnReHold", false);
        funEnabledBtn("btnHold", true);
    } else {
        writeInfo("发送恢复指令失败");
    }
}

// 会议接口
function funConfAdd(vIntJuXiang, vStrXSCaller, vStrCallee) {
    writeInfo("局向：" + vIntJuXiang + ";主叫：" + vStrXSCaller + ",被叫：" + vStrCallee);
    try {
        Start3Conf(vStrCallee, strFJH, CallSerialNumber, vStrXSCaller);
    } catch (e) {
        alert("异常错误，请重试。" + e.description);
    }
    return 1;
}

// 转接接口
function funToTrans(vStrCallee) {
    writeInfo(vStrCallee);
    var n = TransferCall(vStrCallee, strFJH, CallSerialNumber);
    if (n == 1) writeInfo("执行转接成功");
    else {
        writeInfo("执行转接失败");
    }
}

// 咨询接口
function funConsultation(vStrCallee) {
    //var n = document.all.axDRSLC.drtConsultation(2, strShowNum, vStrCallee, 30);
    if (n == 1) writeInfo("执行咨询成功");
    else {
        writeInfo("执行咨询失败");
    }
}

//监听接口
function funSetListen(vStrCaller) {
    writeInfo("监听:" + vStrCaller);
    return AgentListen(vStrCaller, strFJH); //document.all.axDRSLC.drtAdminListenAgentStart(vStrCaller);
}

//监听接口-扩展
function funSetListenEx(vDirect, vStrCaller) {
    writeInfo("监听Ex:" + vStrCaller + "局向:" + vDirect);
    //return document.all.axDRSLC.drtAdminListenAgentStartEx(vDirect, vStrCaller, strFJH, 30);
}

//强插接口
function funSetInsert(vStrCaller) {
    writeInfo("强插:" + vStrCaller);
    return AgentInsert(strFJH, vStrCaller) //document.all.axDRSLC.drtAdminFocreInsert(strFJH, vStrCaller);
}

//强插接口-扩展
function funSetInsertEx(vDirect, vStrCaller) {
    writeInfo("强插Ex:" + vStrCaller + "局向：" + vDirect);
    return document.all.axDRSLC.drtAdminFocreInsertEx(vDirect, strFJH, vStrCaller, 30);
}

//强拆接口
function funSetHook(vStrCallee) {
    writeInfo("强拆:" + vStrCallee);
    return HangUp()//document.all.axDRSLC.drtAdminFocreHook(vStrCallee);
}

//强签接口
function funSetLogout(vStrWrkName, vStrCaller) {
    writeInfo("强签:" + vStrCaller);
    return document.all.axDRSLC.drtAdminFocreLogout(vStrWrkName, vStrCaller);
}

//发送传真接口
function funSendFax(vStrFaxFile) {
    if (nResult != 1) return;
    try {
        document.all.axDRSLC.SetToFax(vStrFaxFile);
    } catch (e) {
        alert('[' + vStrFaxFile + ']发送失败。');
    }
}

//发送dtmf码接口
function funSendDtmf(str) {
    try {
        var n = document.all.axDRSLC.SetSendDtmf(str);
        if (n == 1)
            writeInfo("发送dtmf码“" + str + "”成功");
        else
            writeInfo("发送dtmf码“" + str + "”失败");
    } catch (e) {
        writeInfo(e.description);
    }
}

//设置座席类型接口
function funSetSLCType(vStrSLCType) {
    if (nResult != 1) return;
    var n = document.all.axDRSLC.drtSetAgentType(parseInt(vStrSLCType));
    if (n == 1) {
        writeInfo("发送设置座类型指令成功。" + vStrSLCType);
    } else writeInfo("发送设置座类型指令失败。");
}

//获得座席类型接口
function funGetSLCType() {
    var n = document.all.axDRSLC.drtGetAgentType();
    if (n == 1) {
        writeInfo("发送获得座席类型指令成功。");
    } else writeInfo("发送获得座席类型指令失败。");
}

//刷新座席状态列表接口
function funReflashAgentStateList() {

}

/*=======================================自定义事件处理======================================================*/

// 班长座席登录结果事件
function eventAdminLogin(vStrQueueName, vStrUsrName, vStrUsrPwd, vIntResult, vStrMsg) {
    writeInfo("eventAdminLogin[" + vStrUsrName + "][" + vStrUsrPwd + "][" + vIntResult + "]");
    if (vIntResult == 1) {

        if (strIsAdmin == "1" && vStrUsrName == strGH) {
            writeInfo("班长席签入成功");
            funAdminBtnEnable(true);
            funEnabledBtn("btnLogOut", true);
            funEnabledBtn("btnCall", true);
            funEnabledBtn("btnAnswer", false);
            funEnabledBtn("btnSet", true);
            funEnabledBtn("btnFax", true);
            funEnabledBtn("btnReady", true);
            funEnabledBtn("btnLeave", true);
            if (blIsConf)                    //判断是否开启了会议功能
            {
                funEnabledBtn("btnMeeting", true);
            }
            funDisplayBtn("btnLogin", false);
            funDisplayBtn("btnLogOut", true);
            funDisplayBtn("btnReady", false);
            funDisplayBtn("btnLeave", true);
            //funSetSLCType("1");           //登录后默认类型为：软座席

            funMgrSLC1(strFJH, vStrUsrName, vStrQueueName, "就绪", getDate(), "", true);
            document.all.axDRSLC.drtReflashAgentStateList();
            blLogined = true;
            setActionName("签入");
        }
        document.all.axDRSLC.drtSetAgentType(strSLCType);
    } else {
        if (strIsAdmin == "1" && vStrUsrName == strGH) {
            alert('签入失败：' + vStrMsg);
            writeInfo("签入失败--" + vStrMsg);
        }
    }
}

// 普通座席登录结果
function eventUsrLogin(vStrQueueName, vStrUsrName, vStrUsrPwd, vStrCaller, vIntResult, vStrMsg) {
    //window.clearInterval(c);
    //writeInfo("eventUsrLogin[" + vStrUsrName + "][" + vStrCaller + "][" + vIntResult + "]");
    if (vIntResult == 1) {

        if (strIsAdmin == "0" && vStrUsrName == strGH) //不是管理员且为自已的工号
        {

            funEnabledBtn("btnLogOut", true);
            funEnabledBtn("btnCall", true);
            funEnabledBtn("btnAnswer", false);
            funEnabledBtn("btnSet", true);
            funEnabledBtn("btnFax", true);
            funEnabledBtn("btnReady", true);
            funEnabledBtn("btnLeave", true);
            if (blIsConf)    //如果开启了会议功能
            {
                funEnabledBtn("btnMeeting", true);
            }
            funDisplayBtn("btnLogin", false);
            funDisplayBtn("btnLogOut", true);
            funDisplayBtn("btnReady", false);
            funDisplayBtn("btnLeave", true);
            funReflashAgentStateList(); //刷新座席状态列表
            blLogined = true;
            setActionName("签入");
            funMgrSLC1(vStrCaller, vStrUsrName, vStrQueueName, "就绪", getDate(), "", true);
        }
        //这是调用了什么
        //document.all.axDRSLC.drtSetAgentType(strSLCType);
    } else {
        if (vStrUsrName == strGH) {
            alert('签入失败：' + vStrMsg);
            //writeInfo("签入失败--" + vStrMsg);
        }
    }
}

// 注销结果
function eventUsrLogout(vStrQueueName, vStrUsrName, vStrUsrPwd, vStrCaller, vIntResult) {
    //writeInfo("eventUsrLogout[" + vStrUsrName + "][" + vIntResult + "][" + vStrCaller + "][" + strFJH + "]");
    if (true) {
        if (strIsAdmin == "1") //如果是班长席，设置监控按钮都不可用,班长席签出也用此函数
            funAdminBtnEnable(false);
        writeInfo("签出成功");
        funDisplayBtn("btnHold", true);
        funDisplayBtn("btnReHold", false);
        funDisplayBtn("btnLogin", true);
        funDisplayBtn("btnLogOut", false);
        funDisplayBtn("btnLeave", true);
        funDisplayBtn("btnReady", false);
        funAllBtnEnabled(false); //设置所有按钮不可用
        funEnabledBtn("btnLogin", true);
        blLogined = false;
        blCallOut = false;
        setActionName("未签入");
        funMgrSLC1(vStrCaller, "", "", "", "", "", false);
    } else {
        if (vStrCaller == strFJH) {
            writeInfo("签出失败--" + vStrMsg);
        }
    }
}

function ReflashStatesEventEx(vIntSate, vIntType, vStrCaller, vStrCallee, vStrStartTime, vStrEndTime) {
    //更新座席状态
    if ((vIntSate != 1) && (vIntType == 2 || vIntType == 8))	//如果电话是呼入状态分机号码取主叫号码
    {
        funMgrSLC(vStrCallee, "", vStrStartTime, getSLCStatus(vIntSate, vIntType));
        writeInfo("座席状态：[" + vStrCallee + "],[" + vIntSate + "],[" + vIntType + "],[" + vStrCallee + "],[" + getSLCStatus(vIntSate, vIntType) + "]");
    } else {
        writeInfo("座席状态：[" + vStrCaller + "],[" + vIntSate + "],[" + vIntType + "],[" + vStrCallee + "],[" + getSLCStatus(vIntSate, vIntType) + "]");
        funMgrSLC(vStrCaller, "", vStrStartTime, getSLCStatus(vIntSate, vIntType));
    }

    //writeInfo("座席状态11s：[" + vStrCaller + "],[" + getSLCStatus(vIntSate,vIntType) + "(" +vIntSate+","+vIntType + ")],[" + vStrCallee + "],[" + vStrStartTime + "],[" + vStrEndTime+"]");
    if (vStrCaller == strFJH) {
        if (vIntSate == 2 || vIntSate == 4) {
            if (strSLCType == "0") return;
            funEnabledBtn("btnSoftHook", true);
        } else if (vIntSate == 8) {
            if (strSLCType == "1") funEnabledBtn("btnAnswer", false);
        } else if (vIntSate == 9) {
            funEnabledBtn("btnSoftHook", true);
        } else if (vIntSate == 15) {
            if (strSLCType == "0") return;
            if (vIntType == 7) funEnabledBtn("btnAnswer", false);
            else if (vIntType == 8) funEnabledBtn("btnSoftHook", true);
        }
    }
}

// 班长席登录后通过此事件获取其他座席登录状态
function eventReflashStatesLogin(vStrQueueName, vStrUsrName, vStrCaller, vStrLoginTime) {
    //writeInfo("座席登录状态：[" + vStrQueueName + "],[" + vStrUsrName + "],[" + vStrCaller + "],[" + vStrLoginTime+"]");
    funMgrSLC1(vStrCaller, vStrUsrName, vStrQueueName, "就绪", vStrLoginTime, "", true);
}

// 设置小休事件
function eventLeave(vStrCaller, vIntResult) {
    //writeInfo("eventLeave(" + vStrCaller + "," + vIntResult + ")");
    // if (vIntResult == 1) {
    //updateSLCListEx(vStrCaller, "小休");
    //小休为6
    if (vIntResult == 6) {
        //writeInfo("设置小休成功");
        funDisplayBtn("btnReady", true);
        funDisplayBtn("btnLeave", false);
        setActionName("小休");
    } else if (vIntResult == 2) {
        // writeInfo("设置置忙成功");
        funDisplayBtn("btnReady", true);
        funDisplayBtn("btnLeave", false);
        setActionName("置忙");
    }
}

//设置就绪事件
function eventReady(vStrCaller, vIntResult) {
    //writeInfo("eventReady(" + vStrCaller + "," + vIntResult + ")");
    if (vIntResult == 1) {
        //updateSLCListEx(vStrCaller, "就绪");
        if (vStrCaller == strFJH) {
            writeInfo("设置就绪成功");
            funDisplayBtn("btnLeave", true);
            funDisplayBtn("btnReady", false);
            setActionName("就绪");
        }
    } else {
        if (vStrCaller == strFJH) {
            writeInfo("设置就绪失败");
        }
    }
}

//设置座席类型事件
function eventSlcType(vIntSLCType, vIntResult) {
    if (vIntResult == 1) {
        strSLCType = vIntSLCType;
        writeInfo('设置座席类型成功。' + strSLCType);
    } else {
        writeInfo('设置座席类型失败。');
    }
}

//获得座席类型事件
function eventGetAgentType(vIntSLCType, vIntResult) {
    if (vIntResult == 1) {
        writeInfo("获取座席类型成功，类型为：" + vIntSLCType);
        strSLCType = vIntSLCType;
    } else {
        writeInfo("获取座席类型失败");
    }
}

//座席摘机事件
function eventOccupy(vCallerID) {
    writeInfo(vCallerID + "摘机");
    updateSLCList(vCallerID, "占用", "");
    if (vCallerID == strFJH) {
        var objBtn = document.getElementById("btnHold");
        if (objBtn) {
            funEnabledBtn("btnHold", true);
            funDisplayBtn("btnHold", true);
        }
        //if(strSLCType=="0")
        funEnabledBtn("btnSoftHook", true);
        funEnabledBtn("btnCall", true);
        funEnabledBtn("btnLeave", false);
        funEnabledBtn("btnReady", false);
        funEnabledBtn("btnLogin", false);
        funEnabledBtn("btnLogOut", false);
        setActionName("摘机");
    }
}

//收到忙音事件
function eventBusyVoice(vStrCaller) {
    updateSLCList(vStrCaller, "忙音", "");//更新座席状态
    if (vStrCaller == strFJH) {
        funEnabledBtn("btnSoftHook", true);
        funEnabledBtn("btnCall", false);
        writeInfo('收到忙音。');
        setActionName("忙音");
    }
}

//网络延迟事件
function eventLinkTimerOut(vIntTimes) {
    document.all.lblTimes.innerText = vIntTimes;
}

//进入队列事件
function eventAddQueue(vStrQueueName, vStrCaller, vStrJoinTime) {
    CountQueue("add");  //统计排队人数
    writeInfo("加入队列：[" + vStrQueueName + "],[" + vStrCaller + "],[" + vStrJoinTime + "]");
}

//退出队列事件
function eventLeaveQueue(vStrQueueName, vStrCaller) {
    CountQueue("leave"); //统计排队人数
    writeInfo("退出队列：[" + vStrQueueName + "],[" + vStrCaller + "]");
}

//座席振铃事件--来电弹屏 普通座席修改自己的状态，班长席修改座席监控状态
function eventRingTo(vStrCaller, vStrCallee, vStrRecFile, vStrSerial) {
    updateSLCList(vStrCallee, "振铃", strCaller); //更新座席状态
    if (vStrCallee === strFJH) {
        /* var span = document.createElement("span");
         span.style.color="red";
         span.innerText=vStrCaller;*/
        writeInfo("来电了：[" + vStrCaller + "],[" + vStrCallee + "]")
        blCallin = true;
        setActionName("振铃");
        funEnabledBtn("btnAnswer", false);
        funEnabledBtn("btnSoftHook", true);
        var strCaller = vStrCaller + ",";
        var arr = vStrCaller.split(',');
        strCaller = arr[0] + '-';
        var arr1 = strCaller.split('-');
        strCaller = arr1[0];
        if (vStrCallee !== vStrCaller) {
            document.all.txtTelNO.value = strCaller;
            var doNum;
            if (vStrRecFile === '1') {
                doNum = "燃气泄漏"
            }
            if (vStrRecFile === '2') {
                doNum = "燃气故障报修"
            }
            if (vStrRecFile === '3') {
                doNum = "燃气缴费咨询"
            }
            if (vStrRecFile === '4') {
                doNum = "燃气补卡过户"
            }
            if (vStrRecFile === '5') {
                doNum = "人工服务"
            }

            var objTxt = document.getElementById("txtInfo");
            var newDivs = document.createElement("div");
            var newDiv = document.createElement("span");
            var newRed = document.createElement("span");
            var newEND = document.createElement("span");
            newDivs.className = "doInput"
            newDivs.style.textAlign = "left";
            newDiv.innerText = new Date().Format("yyyy-MM-dd HH:mm:ss") + " 来电号码：["
            newRed.style.color = "red"
            newRed.innerText = strCaller
            newEND.innerText += "]" + "\t用户按键串：\t[" + doNum + "]"
            newDivs.appendChild(newDiv)
            newDivs.appendChild(newRed)
            newDivs.appendChild(newEND)
            if ($(".doInput")[0] === undefined) {
                objTxt.appendChild(newDivs)
            } else {
                objTxt.insertBefore(newDivs, $(".doInput")[0]);
            }
            //writeInfo("来电了：[" + vStrCaller + "],[" + vStrCallee + "],[" + vStrRecFile + "],[" + vStrSerial + "]");
        }
        strConfNOs = '';

    }
}

//在来电呼叫座席时发生
function eventRingBack(vStrCaller, vStrCallee, vStrRecFile, vStrSerial) {
    updateSLCList(vStrCaller, "呼叫", "");    //更新此座席的状态
    if (vStrCaller == strFJH) setActionName("呼叫中...");
}

//应答摘机 普通座席修改自己的状态，班长席修改座席监控状态
function eventOffHook(vStrCaller) {
    writeInfo("应答摘机：[" + vStrCaller + "]");
    updateSLCList(vStrCaller, "通话", "");    //更新座席状态
    if (vStrCaller == strFJH) {
        writeInfo("通话：[" + vStrCaller + "]");
        funEnabledBtn("btnFax", true);
        if (blCallin) {
            funEnabledBtn("btnHold", true);
            funEnabledBtn("btnTran", true);
        }
        funEnabledBtn("btnAnswer", false);
        funEnabledBtn("btnCall", false);
        funEnabledBtn("btnSoftHook", true);
        funEnabledBtn("btnLeave", false);
        funEnabledBtn("btnReady", false);
        funEnabledBtn("btnLogin", false);
        funEnabledBtn("btnLogOut", false);
        if (strIsAdmin == "1")                 //如果是班长席，设置监控按钮都不可用
            funAdminBtnEnable(false);
        nTimer = 1;
        blTimer = true;
        //setTimer()
        timer = window.setTimeout("setTimer()", 1000);
        blCalling = true;
        setActionName("通话");
    }
}

// 挂机 普通座席修改自己的状态，班长席修改座席监控状态
function eventHook(vStrCaller, str) {
    console.log('话机挂机');
    console.log('客户id：' + $('#callCustomerId').val());
    updateSLCList(vStrCaller, "空闲", "");    //更新座席状态

    writeInfo("挂机：[" + vStrCaller + "];分机：" + strFJH + "");
    //setActionName("挂机");
    //writeInfo("挂机：[" + vStrCaller + "]");
    blTimer = false;
    blCalling = false;
    // 修改按钮状态
    funEnabledBtn("btnSoftHook", false);
    funEnabledBtn("btnHold", false);
    funEnabledBtn("btnReHold", false);
    funDisplayBtn("btnReHold", false);
    funEnabledBtn("btnCall", true);
    funEnabledBtn("btnTran", false);
    funEnabledBtn("btnOneKey", false);
    blCallin = false;
    blCallOut = false;
    window.clearTimeout(timer);
    window.clearInterval(callinTimer);
    callinTimer = null;
    funEnabledBtn("btnLeave", true && blLogined);
    funEnabledBtn("btnReady", true && blLogined);
    funEnabledBtn("btnLogin", true);
    funEnabledBtn("btnLogOut", true);
    funEnabledBtn("btnAnswer", false);
    if (strIsAdmin == "1")                   //如果是班长席，设置监控按钮都不可用
        funAdminBtnEnable(true);
    // 清空会议号码
    strConfNOs = "";
    //清除来电号码
    var strAct = "就绪";
    setActionName(strAct);
    // 挂断后获取相关通话记录信息
    getCallInfo(str);

    // 清除联系人列表选中状态
    if ($('#callCustomerId').val() !== '') {
        $('input[name="phoneNumber"]').attr('checked', false);
    }
    // 清除通话人名并隐藏
    $('.tell-name').fadeOut('normal', function () {
        $(this).find('span').html('');
    });
}

//重新连接服务器事件
function eventReLogining() {
    funAllBtnEnabled(false);                  //设置所有按钮是否可用
    blLogined = false;
    blCallOut = false;
    setActionName("连接中");
}

//连接断开事件
function eventClose() {
    funAllBtnEnabled(false);                  //设置所有按钮是否可用
    blLogined = false;                        //更改登录状态
    funMgrSLC1(strFJH, "", "", "", "", "", false);  //更新座席状态
    setActionName("断开");                    //设置操作名称
}

//返回错误原因事件
function eventErrorReason(vStrErrorMsg) {
    writeInfo(vStrErrorMsg);
}

/*
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtLoginEvent(vStrQueueName,vStrUsrName,vStrUsrPwd,vStrCaller,vIntResult,vStrMsg)">
    //普通座席签入事件
    eventUsrLogin(vStrQueueName, vStrUsrName, vStrUsrPwd, vStrCaller, vIntResult, vStrMsg
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtLogoutEvent(vStrQueueName,vStrUsrName,vStrUsrPwd,vStrCaller,vIntResult)">
    //普通座席签出事件
    eventUsrLogout(vStrQueueName, vStrUsrName, vStrUsrPwd, vStrCaller, vIntResult
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtAdminLoginEvent(vStrQueueName,vStrUsrName,vStrUsrPwd,vStrCaller,vIntResult,vStrMsg)">
    //班长座席签入事件
    eventAdminLogin(vStrQueueName, vStrUsrName, vStrUsrPwd, vIntResult, vStrMsg
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtAdminLogoutEvent(vStrQueueName,vStrUsrName,vStrUsrPwd,vStrCaller,vIntResult)">
    //班长座席签出事件
    eventUsrLogout(vStrQueueName, vStrUsrName, vStrUsrPwd, vStrCaller, vIntResult
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtInitQueueEvent(vStrQueueName,vQueueNumber)">
    //初始化工组事件
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtLeaveEvent(vStrOptType,vStrCaller,vIntResult)">
    //小休/置忙事件
    eventLeave(vStrCaller, vIntResult
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtWorkingEvent(vStrCaller,vIntResult)">
    //事后处理事件
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtReadyEvent(vStrOptType,vStrCaller,vIntResult)">
    //就绪/置闲事件
    eventReady(vStrCaller, vIntResult
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtSetAgentTypeEvent(vIntSLCType,vIntResult)">
    //设置座席类型事件
    eventSlcType(vIntSLCType, vIntResult
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtGetAgentTypeEvent(nType,nResult)">
    //获取座席类型事件
    eventGetAgentType(nType, nResult
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtOccupyEvent(vCallerID)">
    //座席摘机事件
    eventOccupy(vCallerID);
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtBusyVoiceEvent(vCallerID)">
    //座席忙音事件
    eventBusyVoice(vCallerID);
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="OnLinkTimerOutEvent(vIntTimes)">
    eventLinkTimerOut(vIntTimes);
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtReflashAgentStateEvent(vIntSate,vIntType,vStrCaller,vStrCallee,vStrStartTime,vStrEndTime)">
    //刷新座席电话状态事件
    ReflashStatesEventEx(vIntSate, vIntType, vStrCaller, vStrCallee, vStrStartTime, vStrEndTime
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtReflashAgentLoginStateEvent(vStrQueueName,vStrCaller,vStrUsrName,vStrLoginTime)">
    //刷新座席签入状态事件
    eventReflashStatesLogin(vStrQueueName, vStrUsrName, vStrCaller, vStrLoginTime
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtAddQueueEvent(vStrQueueName,vStrCaller,vStrCallee,vStrJoinTime,vStrWaittimes)">
    //客户进入工作组排队事件
    eventAddQueue(vStrQueueName, vStrCaller, vStrJoinTime
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtLeaveQueueEvent(vStrQueueName,vStrCaller)">
    //客户退出工作组排队事件
    eventLeaveQueue(vStrQueueName, vStrCaller
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtRingToEvent(vStrCaller,vStrCallee,vStrFirstCallee,vStrDtmf,vStrRecFile,vStrSerial)">
    //座席振铃/来电弹屏事件
    eventRingTo(vStrCaller, vStrCallee, vStrRecFile, vStrSerial
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC"
        event="drtRingBackEvent(vStrCaller,vStrCallee,vStrRecFile,vStrSerial)">
    //座席回铃/去电弹屏事件
    eventRingBack(vStrCaller, vStrCallee, vStrRecFile, vStrSerial
)
;
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtAnswerEvent(vStrCaller)">
    //应答事件
    eventOffHook(vStrCaller);
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtHookEvent(vStrCaller)">
    //座席挂机事件
    eventHook(vStrCaller);
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtReLoginEvent()">
    //重新签入事件
    eventReLogining();
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtCloseEvent()">
    //重新签入事件
    eventClose();
</script>
<script language="javascript" type="text/javascript" htmlFor="axDRSLC" event="drtErrorReasonEvent(vStrErrorMsg)">
    //返回错误原因事件
    eventErrorReason(vStrErrorMsg);
</script>*/

/*===================电话框及电话拨号盘的相关操作======================================================================*/

var nCountCall = 0; //外呼个数统计
var nDelCount = 0; //删除button个数统计
var LastPhone = ""; //记录最后一次呼出的电话号码，用于是否往呼出电话记录里保存（如同时呼出同一个号码多次就记录一次）
var btnID = 0;

function funSetCall(vObj) {
    var objValue = document.getElementById(vObj).value;
    document.getElementById("txtTelNO").value = objValue;
    oPopup.hide();
}

//记录外呼电话
function funRecCall(vNumber) {
    nCountCall++;
    btnID = nCountCall;
    if (nCountCall > 10) //当外呼数大于10的时候，开始删除第一个，然后再添加的名字从1开始
    {
        nDelCount++;
        if (nDelCount > 10) {
            nDelCount = 1;
        }
        deleteElement("btn" + nDelCount);
        btnID = nDelCount
    }
    var obj = document.getElementById("CallHistoryText");
    if (LastPhone == vNumber) return;  //如同时呼出同一个号码多次就记录一次
    obj.innerHTML = "<input type='button' id='btn" + btnID + "' value='" + vNumber + "'  style='background:#E2F1F8;color:#044377;border:0px;width:156px;height:17px;border-bottom:solid 1px #3399ff' />" + obj.innerHTML;
}

function changeBtnName(vNum) {
}

//var oPopup = window.createPopup();

//弹出外呼历史记录
function funShowCallHostory() {
    var n = 0;
    var popupBodyObj = oPopup.document.body;
    var topper = event.screenY + 8;
    oPopup.document.body.innerHTML = CallHistory.innerHTML;
    oPopup.show(120, topper, 158, 200);
    //show(left,top, width, height, document.body);
    popupBodyObj.innerHTML = document.getElementById("CallHistory").innerHTML;

    for (var i = 0; i < popupBodyObj.all.length; i++) {
        if (popupBodyObj.all[i].tagName == "INPUT") {
            switch (popupBodyObj.all[i].id) {
                case "btn1":
                    popupBodyObj.all[i].ondblclick = funSetCall1;
                    break;
                case "btn2":
                    popupBodyObj.all[i].ondblclick = funSetCall2;
                    break;
                case "btn3":
                    popupBodyObj.all[i].ondblclick = funSetCall3;
                    break;
                case "btn4":
                    popupBodyObj.all[i].ondblclick = funSetCall4;
                    break;
                case "btn5":
                    popupBodyObj.all[i].ondblclick = funSetCall5;
                    break;
                case "btn6":
                    popupBodyObj.all[i].ondblclick = funSetCall6;
                    break;
                case "btn7":
                    popupBodyObj.all[i].ondblclick = funSetCall7;
                    break;
                case "btn8":
                    popupBodyObj.all[i].ondblclick = funSetCall8;
                    break;
                case "btn9":
                    popupBodyObj.all[i].ondblclick = funSetCall9;
                    break;
                case "btn10":
                    popupBodyObj.all[i].ondblclick = funSetCall10;
                    break;
            }
        }
    }
    oPopup.document.all.imgClose.attachEvent("onclick", funPhoneClose);
}

function funSetCall1() {
    funSetCall("btn1");
}

function funSetCall2() {
    funSetCall("btn2");
}

function funSetCall3() {
    funSetCall("btn3");
}

function funSetCall4() {
    funSetCall("btn4");
}

function funSetCall5() {
    funSetCall("btn5");
}

function funSetCall6() {
    funSetCall("btn6");
}

function funSetCall7() {
    funSetCall("btn7");
}

function funSetCall8() {
    funSetCall("btn8");
}

function funSetCall9() {
    funSetCall("btn9");
}

function funSetCall10() {
    funSetCall("btn10");
}

function funPhoneClose() {
    oPopup.hide();
} //隐藏oPopup历史电话记录
//删除节点
function deleteElement(id) {
    var d = document.getElementById(id);
    if (d) {
        var p;
        if (p = d.parentNode) {
            p.removeChild(d);
        }
    }
}

//弹出电话盘
function richContext() {
    var lefter = event.offsetX + 0;
    var topper = event.screenY + 8;
    oPopup.document.body.innerHTML = tbNumber.innerHTML;
    oPopup.document.all.Num1.attachEvent("onclick", funKeyNumber1);
    oPopup.document.all.Num2.attachEvent("onclick", funKeyNumber2);
    oPopup.document.all.Num3.attachEvent("onclick", funKeyNumber3);
    oPopup.document.all.Num4.attachEvent("onclick", funKeyNumber4);
    oPopup.document.all.Num5.attachEvent("onclick", funKeyNumber5);
    oPopup.document.all.Num6.attachEvent("onclick", funKeyNumber6);
    oPopup.document.all.Num7.attachEvent("onclick", funKeyNumber7);
    oPopup.document.all.Num8.attachEvent("onclick", funKeyNumber8);
    oPopup.document.all.Num9.attachEvent("onclick", funKeyNumber9);
    oPopup.document.all.Num0.attachEvent("onclick", funKeyNumber0);
    oPopup.document.all.NumStar.attachEvent("onclick", funKeyNumberStar);
    oPopup.document.all.NumJing.attachEvent("onclick", funKeyNumberJing);

    oPopup.document.all.numBottom.attachEvent("onclick", funNumBottom);
    oPopup.document.all.numBottom.setAttribute("alt", "收起拨号盘");
    oPopup.document.all.numBottomRight.attachEvent("onclick", funNumBottomRight);
    oPopup.document.all.numBottomRight.setAttribute("alt", "退格");

    oPopup.show(90, topper, 158, 160);
    //oPopup.show(90,190,158,160);
    //show(left,top, width, height, document.body);
}

function funKeyNumber1() {
    funKeyNumber("1");
}

function funKeyNumber2() {
    funKeyNumber("2");
}

function funKeyNumber3() {
    funKeyNumber("3");
}

function funKeyNumber4() {
    funKeyNumber("4");
}

function funKeyNumber5() {
    funKeyNumber("5");
}

function funKeyNumber6() {
    funKeyNumber("6");
}

function funKeyNumber7() {
    funKeyNumber("7");
}

function funKeyNumber8() {
    funKeyNumber("8");
}

function funKeyNumber9() {
    funKeyNumber("9");
}

function funKeyNumber0() {
    funKeyNumber("0");
}

function funKeyNumberStar() {
    funKeyNumber("*");
}

function funKeyNumberJing() {
    funKeyNumber("#");
}

function funNumBottom() {
    oPopup.hide();
} //隐藏oPopup窗口
function funNumBottomRight() //退格
{
    funBackSpace("");
}

//写入电话号码
function funKeyNumber(vNum) {
    //document.getElementById("txtTelNO").insertAdjacentText("beforeBegin",vNum);return;
    var obj = document.getElementById("txtTelNO");
    if (vNum != null && vNum != "") {
        obj.value = obj.value + vNum;
        if (blCallOut || blCalling)//如果外拨中,发送dtmf码
        {
            funSendDtmf(vNum);
        }
    }
}

//电话退格
function funBackSpace(type) {
    var obj = document.getElementById("txtTelNO").value;
    if (type != null && type != "") //清除
    {
        document.getElementById("txtTelNO").value = "";
    } else if (obj.length > 1) //退格
    {
        obj = obj.substring(0, obj.length - 1);
        document.getElementById("txtTelNO").value = obj;
    } else if (obj.length = 1) {
        document.getElementById("txtTelNO").value = "";
    }
}
